const router = require('koa-router')()
const fs = require('fs')
const path = require('path')
const mongoose = require('mongoose')
const puppeteer = require('puppeteer')

const url = `https://movie.douban.com/tag/#/?sort=S&range=6,10&tags=`

const sleep = time => new Promise(resolve => {
  setTimeout(resolve, time)
})

const successResponse = (code, msg, data) => {
    return { code, msg, data }
}

router.prefix('/api/crawler')

router
    // 爬取视频列表
    .get('/getCrawler', async ctx => {
      console.log('Start visit the target page')
      try {
        const browser = await puppeteer.launch({
          args: ['--no-sandbox'],
          dumpio: false
        })

        const page = await browser.newPage()
        await page.goto(url, {
          waitUntil: 'networkidle2'
        })

        await sleep(3000)

        await page.waitForSelector('.more')

        for (let i=0;i<1;i++) {
          await sleep(3000)
          await page.click('.more')
        }

        const result = await page.evaluate(() => {
          var $= window.$
          var items = $('.list-wp a')
          var links = []

          if(items.length > 0) {
            items.each((index, item) => {
              let it = $(item)
              let doubanId = it.find('div').data('id')
              let title = it.find('.title').text()
              let rate = Number(it.find('.rate').text())
              let poster = it.find('img').attr('src').replace('s_ratio', 'l_ratio')

              links.push({
                doubanId,
                title,
                rate,
                poster
              })
            })
          }

          return links
        })

      browser.close()

      process.send({result})
      process.exit(0)

      } catch (error) {
          ctx.body = successResponse(503, error, null)
      }
    })
    // 新增视频
    .post('/addMovieList', async ctx => {
        const MovielModel = mongoose.model('Movie')
        let params = JSON.parse(JSON.stringify(ctx.request.body))
        params.movieTypes = params.movieTypes.split(',')
        var movielModel = new MovielModel(params)
        try {
            await movielModel.save()
            ctx.body = successResponse(200, '添加成功', null)
        } catch (err) {
            ctx.body = successResponse(503, '添加失败', null)
        }
    })



module.exports = router
